﻿using System;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Events;
using Autodesk.Revit.UI;

namespace YArchitech.Plumbing
{
	[Regeneration(RegenerationOption.Manual)]
	public class PipeChangeUpdate : IExternalApplication
	{
		Result IExternalApplication.OnShutdown(UIControlledApplication application)
		{
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		Result IExternalApplication.OnStartup(UIControlledApplication application)
		{
			this.m_thisAppId = application.ActiveAddInId;
			application.ControlledApplication.DocumentCreated += this.ControlledApplication_DocumentCreated;
			application.ControlledApplication.DocumentOpened += this.ControlledApplication_DocumentOpened;
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private void ControlledApplication_DocumentCreated(object sender, DocumentCreatedEventArgs e)
		{
			PipeChangeUpdate.m_sectionUpdater = new PipeUpdater(this.m_thisAppId);
			PipeChangeUpdate.m_sectionUpdater.Register(e.Document);
			e.Document.DocumentClosing += this.Document_DocumentClosing;
		}

		private void ControlledApplication_DocumentOpened(object sender, DocumentOpenedEventArgs args)
		{
			PipeChangeUpdate.m_sectionUpdater = new PipeUpdater(this.m_thisAppId);
			PipeChangeUpdate.m_sectionUpdater.Register(args.Document);
			args.Document.DocumentClosing += this.Document_DocumentClosing;
		}

		private void Document_DocumentClosing(object sender, DocumentClosingEventArgs e)
		{
			if (PipeChangeUpdate.m_sectionUpdater != null)
			{
				UpdaterRegistry.UnregisterUpdater(PipeChangeUpdate.m_sectionUpdater.GetUpdaterId());
				PipeChangeUpdate.m_sectionUpdater = null;
			}
		}

		private AddInId m_thisAppId;

		private static PipeUpdater m_sectionUpdater;
	}
}
